package com.shigen.demo.shorturl.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shigen.demo.dao.ShortLinkMapper;
import com.shigen.demo.shorturl.entity.ShortLink;
import com.shigen.demo.shorturl.util.ShortLinkUtils;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @author shigenfu
 * @date 2023/10/14 14:08
 */
@Service
@Slf4j
public class ShortLinkServiceImpl extends ServiceImpl<ShortLinkMapper, ShortLink> implements IShortLinkService {

    @Resource
    private ShortLinkMapper shortLinkMapper;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    public static final String lINK = "link:";
    public static final int TTL = 600;

    @Override
    public String getLink(String code) {
        String originUrl = (String) redisTemplate.opsForValue().get(lINK + code);
        if (StrUtil.isEmpty(originUrl)) {
            originUrl = getLinkFromDb(code);
            redisTemplate.opsForValue().set(lINK + code, originUrl, TTL, TimeUnit.SECONDS);
        }
        return originUrl;
    }

    public String getLinkFromDb(String code) {
        String originUrl = getBaseMapper().getLink(code);
        if (StrUtil.isEmpty(originUrl)) {
            throw new RuntimeException("该地址不存在");
        }
        return originUrl;
    }

    @Override
    public String saveLink(String sourceLink) {
        String code = ShortLinkUtils.generateShortLink(sourceLink);
        log.info("code:{}", code);
        ShortLink shortLink = new ShortLink().setOriginUrl(sourceLink)
            .setShortCode(code)
            .setCreator(10001L)
            .setCreateTime(DateUtil.second(new Date()));
        getBaseMapper().insert(shortLink);
        return code;
    }
}
